package com.lotso.web.module.system.controller;

import com.lotso.web.common.ReqParam;
import com.lotso.web.common.Result;
import com.lotso.web.module.base.AbstractController;
import com.lotso.web.module.organization.entity.Office;
import com.lotso.web.module.organization.service.impl.OfficeServiceImpl;
import com.lotso.web.module.system.entity.Role;
import com.lotso.web.module.system.entity.User;
import com.lotso.web.module.system.service.impl.RoleServiceImpl;
import com.lotso.web.module.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * ClassName: UserController
 * Description: 用户管理
 * Date: 2017/12/27 15:36 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends AbstractController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RoleServiceImpl roleService;
    @Resource
    private PasswordEncoder encoder;
    @Resource
    private OfficeServiceImpl officeService;

    /**
     * 进入用户展示页面
     *
     * @return
     */
    @PreAuthorize("hasAuthority('user:view')")
    @GetMapping
    public String user() {
        return "module/system/user";
    }

    /**
     * 查询用户列表
     */
    @PreAuthorize("hasAuthority('user:view')")
    @ResponseBody
    @GetMapping("/list")
    public Result<User> list(ReqParam reqParam) {
        return userService.list(reqParam);
    }

    /**
     * 进入用户添加或者修改页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editForm")
    public String addUser(Model model) {
        List<Role> roles = roleService.list();
        model.addAttribute("roles", roles);

        // 公司
        ReqParam reqParam = new ReqParam();
        reqParam.setSearchKey("type");
        reqParam.setSearchValue("1");
        List<Office> companys = officeService.list(reqParam);
        model.addAttribute("companys", companys);

        // 部门
        reqParam.setSearchValue("2");
        List<Office> offices = officeService.list(reqParam);
        model.addAttribute("offices", offices);
        return "module/system/user_form";
    }

    /**
     * 添加用户
     **/
    @PreAuthorize("hasAuthority('user:add')")
    @ResponseBody
    @RequestMapping("/add")
    public Result add(User user) {
        if (userService.add(user)) {
            return Result.ok("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 修改用户
     **/
    @PreAuthorize("hasAuthority('user:edit')")
    @ResponseBody
    @RequestMapping("/update")
    public Result update(User user) {
        if (userService.update(user)) {
            return Result.ok("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 修改用户状态
     **/
    @PreAuthorize("hasAuthority('user:delete')")
    @ResponseBody
    @RequestMapping("/updateState")
    public Result updateState(String userId, Integer state) {
        if (userService.updateState(userId, state)) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 重置密码
     **/
    @PreAuthorize("hasAuthority('user:edit')")
    @ResponseBody
    @RequestMapping("/restPwd")
    public Result resetPsw(String userId) {
        if (userService.updatePwd(userId, User.DEFAULT_PWD)) {
            return Result.ok("重置成功");
        } else {
            return Result.error("重置失败");
        }
    }

    /**
     * 修改密码弹窗
     *
     * @return
     */
    @GetMapping("/updatePwd")
    public String updatePsw() {
        return "index/password";
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @ResponseBody
    @PostMapping("/updatePwd")
    public Result updatePsw(String oldPwd, String newPwd) {
        User user = userService.getByUsername(getPrincipalName());
        String password = user.getPassword();
        if (!encoder.matches(oldPwd, password)) {
            return Result.error("原密码输入不正确");
        }

        String id = user.getId();
        if (userService.updatePwd(id, newPwd)) {
            return Result.ok("修改成功");
        } else {
            return Result.error("修改失败");
        }

    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @PreAuthorize("hasAuthority('user:delete')")
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(String userId) {
        if (userService.delete(userId)) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 进入个人信息
     *
     * @param model
     * @return
     */
    @GetMapping("/detail")
    public String detail(Model model) {
        String userName = this.getPrincipalName();
        User user = userService.getDetailByUsername(userName);
        model.addAttribute("user", user);
        return "module/system/user_detail";
    }

    /**
     * 修改个人信息
     *
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/detail")
    public Result detail(User user) {
        if (userService.updateById(user)) {
            return Result.ok("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 上传头像
     *
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/avatar")
    public Result<String> avatar(MultipartFile file) throws IOException {
        String fileName = "global/img/user_head.png";
//        FileUtils.writeByteArrayToFile(new File(fileName), file.getBytes());
        return new Result<>(fileName);
    }
}
